﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DZPK.SocketImpl;

namespace DZPK
{
    public class TestEncryptAndDecrypt
    {
        private static TcpSocket socket = new TcpSocket(null);

        public static byte[] Decrypt(byte[] encrypted, TcpSocket socket, int startPos, int totalLength, int enCode)
        {
            ByteArray bytes = new ByteArray();
            bytes.writeArrayBytes(encrypted);
            TcpSocket.CrevasseBuffer(bytes, startPos, totalLength, enCode, socket.m_RecvByteMap);

            byte[] retBytes = bytes.array.ToArray();

            return retBytes;
        }

        public static void DecryptCase_1()
        {
            FileStream fs = null;
            BinaryReader br = null;
            BinaryWriter wr = null;

            string filename = "decrypte_case_1.bin";

            if (!File.Exists(filename))
            {
                throw new Exception("decrypte_case_1.bin doesn't exist.");
            }

            fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
            br = new BinaryReader(fs);

            long len = fs.Length;

            byte[] encrypted = br.ReadBytes((int)len);
            int enCode = encrypted[8];

            byte[] decrypted = Decrypt(encrypted, socket, TcpSocket.PACKET_HEADER_SIZE, (int)len, enCode);

            FileStream output = new FileStream("case_1_output.bin", FileMode.Create, FileAccess.Write);
            wr = new BinaryWriter(output);

            wr.Write(decrypted);

            wr.Close();
            output.Close();

            br.Close();
            fs.Close();
        }
    }
}
